<template>
  <div class="calculator-container" v-if="visible">
    <div class="calculator">
        <div class="calculator-header">
          <span>Calculator</span>
          <span class="close-btn" @click="$emit('update:visible')">×</span>
        </div>
        
        <div class="calculator-brand">
          <span class="model">TI-108</span>
        </div>
  
        <div class="display">{{ display }}</div>
  
        <div class="keypad">
          <!-- 第一行 -->
          <button class="key function" @click="toggleSign">+/-</button>
          <button class="key function" @click="squareRoot">√</button>
          <button class="key function" @click="percentage">%</button>
          <button class="key operator" @click="setOperator('÷')">÷</button>
  
          <!-- 第二行 -->
          <button class="key memory" @click="memoryRecall">MRC</button>
          <button class="key memory" @click="memorySubtract">M-</button>
          <button class="key memory" @click="memoryAdd">M+</button>
          <button class="key operator" @click="setOperator('×')">×</button>
  
          <!-- 数字键和运算符 -->
          <button class="key number" @click="appendNumber('7')">7</button>
          <button class="key number" @click="appendNumber('8')">8</button>
          <button class="key number" @click="appendNumber('9')">9</button>
          <button class="key operator" @click="setOperator('-')">-</button>
  
          <button class="key number" @click="appendNumber('4')">4</button>
          <button class="key number" @click="appendNumber('5')">5</button>
          <button class="key number" @click="appendNumber('6')">6</button>
          <button class="key operator" @click="setOperator('+')">+</button>
  
          <button class="key number" @click="appendNumber('1')">1</button>
          <button class="key number" @click="appendNumber('2')">2</button>
          <button class="key number" @click="appendNumber('3')">3</button>
          <button class="key operator equals" @click="calculate">=</button>
  
          <button class="key clear" @click="clear">ON/C</button>
          <button class="key number" @click="appendNumber('0')">0</button>
          <button class="key number" @click="appendDecimal">.</button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  const display = ref('0');
  const currentValue = ref(null);
  const storedValue = ref(null);
  const currentOperator = ref(null);
  const memoryValue = ref(0);
  const newNumber = ref(true);
  const lastOperation = ref(null);
  // Define emits
const emit = defineEmits(['close', 'update:visible']);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
// Update close handler
const handleClose = () => {
  emit('close');
  emit('update:visible', false);
};

  // 添加数字
  const appendNumber = (num) => {
    if (newNumber.value) {
      display.value = num;
      newNumber.value = false;
    } else {
      if (display.value === '0') {
        display.value = num;
      } else {
        display.value += num;
      }
    }
  };
  
  // 添加小数点
  const appendDecimal = () => {
    if (!display.value.includes('.')) {
      display.value += '.';
      newNumber.value = false;
    }
  };
  
  // 清除
  const clear = () => {
    display.value = '0';
    currentValue.value = null;
    storedValue.value = null;
    currentOperator.value = null;
    newNumber.value = true;
  };
  
  // 设置运算符
  const setOperator = (operator) => {
    if (currentValue.value && !newNumber.value) {
      calculate();
    }
    currentValue.value = parseFloat(display.value);
    currentOperator.value = operator;
    newNumber.value = true;
  };
  
  // 计算结果
  const calculate = () => {
    if (currentOperator.value && currentValue.value != null) {
      const curr = parseFloat(display.value);
      let result;
  
      switch (currentOperator.value) {
        case '+':
          result = currentValue.value + curr;
          break;
        case '-':
          result = currentValue.value - curr;
          break;
        case '×':
          result = currentValue.value * curr;
          break;
        case '÷':
          if (curr === 0) {
            display.value = 'Error';
            return;
          }
          result = currentValue.value / curr;
          break;
      }
  
      // 处理精度问题
      result = Math.round(result * 1000000) / 1000000;
      
      display.value = result.toString();
      lastOperation.value = {
        operator: currentOperator.value,
        value: curr
      };
      currentValue.value = result;
      newNumber.value = true;
    }
  };
  
  // 正负号切换
  const toggleSign = () => {
    display.value = (parseFloat(display.value) * -1).toString();
  };
  
  // 平方根
  const squareRoot = () => {
    const value = parseFloat(display.value);
    if (value < 0) {
      display.value = 'Error';
      return;
    }
    display.value = Math.sqrt(value).toString();
    newNumber.value = true;
  };
  
  // 百分比
  const percentage = () => {
    const value = parseFloat(display.value);
    display.value = (value / 100).toString();
    newNumber.value = true;
  };
  
  // 内存功能
  const memoryAdd = () => {
    memoryValue.value += parseFloat(display.value);
    newNumber.value = true;
  };
  
  const memorySubtract = () => {
    memoryValue.value -= parseFloat(display.value);
    newNumber.value = true;
  };
  
  const memoryRecall = () => {
    display.value = memoryValue.value.toString();
    newNumber.value = true;
  };
  
  // 键盘事件监听
  onMounted(() => {
    window.addEventListener('keydown', handleKeyPress);
  });
  
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyPress);
  });
  
  const handleKeyPress = (event) => {
    const key = event.key;
    
    // 数字键
    if (/[0-9]/.test(key)) {
      appendNumber(key);
    }
    
    // 运算符
    switch (key) {
      case '+':
        setOperator('+');
        break;
      case '-':
        setOperator('-');
        break;
      case '*':
        setOperator('×');
        break;
      case '/':
        setOperator('÷');
        break;
      case '.':
        appendDecimal();
        break;
      case 'Enter':
        calculate();
        break;
      case 'Escape':
        clear();
        break;
    }
  };
  </script>
  
  <style lang="scss" scoped>
  .calculator-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }
  
  .calculator {
    background-color: #2b4d6f;
    border-radius: 10px;
    padding: 15px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
    width: 300px;
  
    .calculator-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: white;
      margin-bottom: 10px;
  
      .close-btn {
        cursor: pointer;
        font-size: 24px;
        
        &:hover {
          opacity: 0.8;
        }
      }
    }
  
    .calculator-brand {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      color: white;
  
      .ti-logo {
        height: 20px;
        margin-right: 10px;
      }
  
      .model {
        font-size: 18px;
        font-weight: bold;
      }
    }
  
    .display {
      background-color: #f0f0f0;
      padding: 10px;
      margin-bottom: 15px;
      text-align: right;
      font-size: 24px;
      font-family: 'Digital', sans-serif;
      border-radius: 5px;
      min-height: 40px;
      overflow: hidden;
    }
  
    .keypad {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 8px;
  
      .key {
        padding: 15px;
        border: none;
        border-radius: 5px;
        font-size: 18px;
        cursor: pointer;
        transition: all 0.2s;
  
        &:active {
          transform: scale(0.95);
        }
  
        &.number {
          background-color: #ffffff;
          color: #333;
          
          &:hover {
            background-color: #f0f0f0;
          }
        }
  
        &.operator {
          background-color: #e74c3c;
          color: white;
          
          &:hover {
            background-color: darken(#e74c3c, 10%);
          }
  
          &.equals {
            grid-row: span 2;
          }
        }
  
        &.function {
          background-color: #e74c3c;
          color: white;
          
          &:hover {
            background-color: darken(#e74c3c, 10%);
          }
        }
  
        &.memory {
          background-color: #e74c3c;
          color: white;
          
          &:hover {
            background-color: #e74c3c;
          }
        }
  
        &.clear {
          background-color: #e74c3c;
          color: white;
          
          &:hover {
            background-color: #e74c3c
          }
        }
      }
    }
  }
  
  // 响应式设计
  @media (max-width: 400px) {
    .calculator {
      width: 90%;
      
      .key {
        padding: 10px;
        font-size: 16px;
      }
    }
  }
  </style>